package com.hirsi.core.config;

import com.hirsi.core.interceptor.HHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired(required = false)
    private List<HHandlerInterceptor> interceptors;

    //swagger相关接口不拦截
    private final String[] swaggerPaths = {"/doc.html", "/swagger-resources/**", "/webjars/**", "/v3/**", "/favicon.ico"};

    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (interceptors != null) interceptors.forEach(interceptor -> registry.addInterceptor(interceptor)
                .addPathPatterns(interceptor.addPaths())
                .excludePathPatterns("/error")
                .excludePathPatterns(swaggerPaths)
                .excludePathPatterns(interceptor.excludePaths()));
    }

    /**
     * 跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
